package com.cloud.controller;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: TongRui乀
 * @Date: 2019/10/25 17:59
 * @description：
 */
@RestController
public class WebController {

    @ApolloConfig
    private Config config;

    @ApolloConfig("application")
    private Config anotherConfig;

    @ApolloConfig("application-dev")
    private Config ymlConfig;

    @Value("${profile}")
    private String profile;


    @GetMapping("getProfile")
    public String getProfile(){
        return profile;
    }


    @GetMapping("getForApi/{nameSpace}/{keys}")
    public String getForApi(@PathVariable String nameSpace, @PathVariable String keys){

//        Config appConfig = ConfigService.getConfig(nameSpace);

        Config appConfig = ConfigService.getAppConfig();

        return appConfig.getProperty(keys, "default");
    }

    @ApolloConfigChangeListener("application")
    public void listener(ConfigChangeEvent changeEvent){
        System.out.println("AAAAA Changes for namespace " + changeEvent.getNamespace());
        for (String key : changeEvent.changedKeys()) {
            ConfigChange change = changeEvent.getChange(key);
            System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
        }
    }

    @GetMapping("getByInject")
    public String getByInject(){
        return this.anotherConfig.getProperty("test", "default");
    }


    @GetMapping("getOtherNS")
    public String getOtherNS(){
        return this.ymlConfig.getProperty("test", "default-test");
    }

}
